package com.qianfeng.android.baoman;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.qianfeng.android.baoman.adapter.CommonFragmentAdapter;
import com.qianfeng.android.baoman.adapter.TopicArticleAdapter;
import com.qianfeng.android.baoman.fragment.TopicPagerFragment;
import com.qianfeng.android.baoman.model.Article;
import com.qianfeng.android.baoman.model.Jokable;
import com.qianfeng.android.baoman.model.JokePoint;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;


public class TopicActivity extends BaseActivity implements ViewPager.OnPageChangeListener, RadioGroup.OnCheckedChangeListener, PullToRefreshBase.OnRefreshListener2<ListView>, AdapterView.OnItemClickListener, TopicArticleAdapter.IEnjoyListener {
    public static final String URL1 = "http://api.ibaozou.com/api/v2/groups/%s/%s/page/%s/%s";
    public static final String URL2 = "http://api.ibaozou.com/api/v2/joke_points";
    private TopicArticleAdapter articleAdapter;
    private LinkedList<Article> articles;
    private ViewPager pager;
    private LinearLayout load_layout;
    private View image_error;
    private MyRunnable myRunnable = new MyRunnable();
    private android.os.Handler handler = new android.os.Handler();
    private int index;
    private HttpUtils httpUtils;
    private PullToRefreshListView pullToRefreshListView;
    private ListView listView;
    //判断进程是否执行的标记
    private boolean mark = true;

    private int kindId = 1;
    private String kind = "recent_hot";

    private int page = 2;
    private int size = 5;

    // at com.handmark.pulltorefresh.library.PullToRefreshListView$InternalListView.dispatchDra


    private boolean flag;


    //    private List<Fragment> fragments;
    private SlidingMenu slidingMenu;
    private ImageButton btnGanhuo;
    private ImageButton btnGif;
    private ImageButton btnNaocan;
    private ImageButton btnQutu;
    private ImageButton btnTucao;
    private ImageButton btnNencao;
    private ImageButton btnBaozou;
    private RadioGroup group;
    private DbUtils dbUtils;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_topic);
        //初始化BitmapHelp!
        BitmapHelp.initUtils(this);
        //初始化ActionBar
        setActionBarTitle("最热门");
        setBackVisible(false);
        setFunctionVisible(false);
        //设置默认的RadioButton点击事件
        setChildRadioChecked(0);
        //数据库
        dbUtils = getDbUtils();

        //slidingmenu
        slidingMenu = new SlidingMenu(this, SlidingMenu.SLIDING_CONTENT);
        slidingMenu.setMenu(R.layout.slidingmenu);
        slidingMenu.setBehindScrollScale(0);
        //获取屏幕宽度的3/7
        WindowManager m = this.getWindowManager();
        Display d = m.getDefaultDisplay();
        int width = d.getWidth();
        int slidingmenuWidth = width / 11 * 6;
        slidingMenu.setBehindOffset(slidingmenuWidth);

        //边界滑动，可以避免与viewpager的冲突
        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
        //属性动画

        Intent intent = getIntent();
        boolean firstLoad = intent.getBooleanExtra("firstLoad", false);
        if (firstLoad) {

            ImageView ico = (ImageView) findViewById(R.id.main_splash_ico);
            ico.setVisibility(View.VISIBLE);
            ObjectAnimator.ofFloat(ico, "translationX", ico.getX(), width).setDuration(2000).start();
            ObjectAnimator.ofFloat(ico, "rotationX", 0.0F, 360.0F).setDuration(1000).start();
        }


        //////////////////////////SlidingMenu相关设置/////////////////////////
        btnBaozou = (ImageButton) findViewById(R.id.sliding_baozou);
        btnGanhuo = (ImageButton) findViewById(R.id.sliding_ganhuo);
        btnGanhuo.setBackgroundResource(R.drawable.ganhuo_pressed);
        btnGif = (ImageButton) findViewById(R.id.sliding_gif);
        btnNaocan = (ImageButton) findViewById(R.id.sliding_naocan);
        btnQutu = (ImageButton) findViewById(R.id.sliding_qutu);
        btnTucao = (ImageButton) findViewById(R.id.sliding_tucao);
        btnNencao = (ImageButton) findViewById(R.id.sliding_nencao);

        btnBaozou.setOnClickListener(this);
        btnGanhuo.setOnClickListener(this);
        btnGif.setOnClickListener(this);
        btnNaocan.setOnClickListener(this);
        btnQutu.setOnClickListener(this);
        btnTucao.setOnClickListener(this);
        btnNencao.setOnClickListener(this);


        ////////////////////布局设置//////////////////////////
        load_layout = (LinearLayout) findViewById(R.id.load_layout);

        load_layout.setVisibility(View.VISIBLE);

        //设置下拉刷新相关属性
        pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.topic_articles);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        pullToRefreshListView.setOnRefreshListener(this);
        //listView
        listView = pullToRefreshListView.getRefreshableView();
        articles = new LinkedList<>();
        articleAdapter = new TopicArticleAdapter(this, articles);
        articleAdapter.setiEnjoyListener(this);
        LayoutInflater layoutInflater = getLayoutInflater();
        View view = layoutInflater.inflate(R.layout.item_topic_pager, null, false);

        listView.addHeaderView(view);
        pager = (ViewPager) view.findViewById(R.id.topic_pager);
        group = (RadioGroup) view.findViewById(R.id.topic_pager_switch);

        View v = group.getChildAt(0);
        if (v != null) {
            if (v instanceof RadioButton) {
                RadioButton rb = (RadioButton) v;
                rb.setChecked(true);
            }
        }


        listView.setAdapter(articleAdapter);
        listView.setOnItemClickListener(this);

        image_error = findViewById(R.id.topic_image_error);
        listView.setVisibility(View.GONE);

        String url = String.format(URL1, String.valueOf(kindId), kind, "1", String.valueOf(size));
        executeHttp(url, URL2);
    }

    @Override
    public void onEnjoy(Article article, Boolean b) {
        try {
            if (b) {
                dbUtils.save(article);
            } else {
                dbUtils.delete(article);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    class MyRunnable implements Runnable {

        @Override
        public void run() {
            if (mark) {
                index++;
                index = index % 4;
                pager.setCurrentItem(index, true);
                handler.postDelayed(myRunnable, 5000);
            }
        }
    }

    @Override
    protected void onDestroy() {
        mark = false;
        super.onDestroy();
    }

    //下拉刷新，上拉加载回调函数
    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        flag = true;
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                String url = String.format(URL1, String.valueOf(kindId), kind, "1", String.valueOf(size));
                executeHttp(url, URL2);
            }
        }, 2000);

    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                String url = String.format(URL1, String.valueOf(kindId), kind, String.valueOf(page), String.valueOf(size));
                executeHttp(url, URL2);
                page++;
            }
        }, 2000);

    }

    /**
     * 两个异步任务请求和相应
     */
    private void executeHttp(final String url1, String url2) {
        httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET, url1, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> stringResponseInfo) {
                String result = stringResponseInfo.result;
                LinkedList<Article> articleLinkedList = new LinkedList<>();

                load_layout.setVisibility(View.GONE);
                image_error.setVisibility(View.GONE);
                listView.setVisibility(View.VISIBLE);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONArray jsonArray = jsonObject.getJSONArray("articles");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject object = jsonArray.getJSONObject(i);
                        Article article = new Article();
                        article.parseJSON(object);
                        articleLinkedList.add(article);
                    }
                    if (flag) {
                        articles.clear();
                    }
                    articles.addAll(articleLinkedList);
                    articleAdapter.notifyDataSetChanged();
                    //关闭菜单，收起下拉，上来布局
                    pullToRefreshListView.onRefreshComplete();
                    flag = false;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(TopicActivity.this, "加载失败，网络问题", Toast.LENGTH_SHORT).show();
                image_error.setVisibility(View.VISIBLE);
                pullToRefreshListView.setVisibility(View.GONE);
                load_layout.setVisibility(View.GONE);
                pullToRefreshListView.setMode(PullToRefreshBase.Mode.DISABLED);
            }
        });

        httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET, url2, new RequestCallBack<String>() {

            private LinkedList<Fragment> fragmentLinkedList;

            @Override
            public void onSuccess(ResponseInfo<String> stringResponseInfo) {

                load_layout.setVisibility(View.GONE);
                image_error.setVisibility(View.GONE);
                listView.setVisibility(View.VISIBLE);
                String result = stringResponseInfo.result;
                fragmentLinkedList = new LinkedList<>();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONArray jsonArray = jsonObject.getJSONArray("joke_points");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject object = jsonArray.getJSONObject(i);
                        JokePoint jokePoint = new JokePoint();
                        jokePoint.parseJSON(object);
                        Jokable jokable = jokePoint.getJokable();

                        TopicPagerFragment topicPagerFragment = new TopicPagerFragment();
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(
                                "joke_point",
                                jokePoint
                        );
                        bundle.putSerializable("jokable", jokable);
                        topicPagerFragment.setArguments(bundle);
                        fragmentLinkedList.add(topicPagerFragment);
                    }

                    CommonFragmentAdapter commonFragmentAdapter = new CommonFragmentAdapter(getSupportFragmentManager(), fragmentLinkedList);

                    if (pager != null) {
                        pager.setAdapter(commonFragmentAdapter);
                        pager.setOnPageChangeListener(TopicActivity.this);
                        group.setOnCheckedChangeListener(TopicActivity.this);
                        handler.postDelayed(myRunnable, 5000);
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(TopicActivity.this, "加载失败，网络问题", Toast.LENGTH_SHORT).show();
                image_error.setVisibility(View.VISIBLE);
                pullToRefreshListView.setVisibility(View.GONE);
                load_layout.setVisibility(View.GONE);
                pullToRefreshListView.setMode(PullToRefreshBase.Mode.DISABLED);
            }
        });
    }

    /*
      干货 1
      脑残 295
      GIF 25
      暴走 19
      趣图 24
      神吐槽 28
      嫩草 1/latest
       */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.sliding_baozou:


                btnBaozou.setBackgroundResource(R.drawable.baozou_pressed);
                btnGanhuo.setBackgroundResource(R.drawable.ganhuo);
                btnGif.setBackgroundResource(R.drawable.gif);
                btnNaocan.setBackgroundResource(R.drawable.naocan);
                btnNencao.setBackgroundResource(R.drawable.nencao);
                btnQutu.setBackgroundResource(R.drawable.qutu);
                btnTucao.setBackgroundResource(R.drawable.tucao);


                //请求网络
                setActionBarTitle("暴走漫画");
                kindId = 19;
                flag = true;
                String url = String.format(URL1, String.valueOf(kindId), kind, "1", String.valueOf(size));
                executeHttp(url, URL2);
                slidingMenu.toggle();
                break;
            case R.id.sliding_ganhuo:
                btnBaozou.setBackgroundResource(R.drawable.baozou);
                btnGanhuo.setBackgroundResource(R.drawable.ganhuo_pressed);
                btnGif.setBackgroundResource(R.drawable.gif);
                btnNaocan.setBackgroundResource(R.drawable.naocan);
                btnNencao.setBackgroundResource(R.drawable.nencao);
                btnQutu.setBackgroundResource(R.drawable.qutu);
                btnTucao.setBackgroundResource(R.drawable.tucao);


                //请求网络
                setActionBarTitle("最热门");
                kindId = 1;
                flag = true;
                url = String.format(URL1, String.valueOf(kindId), kind, "1", String.valueOf(size));
                executeHttp(url, URL2);
                slidingMenu.toggle();
                break;
            case R.id.sliding_gif:
                btnBaozou.setBackgroundResource(R.drawable.ganhuo);
                btnGanhuo.setBackgroundResource(R.drawable.ganhuo);
                btnGif.setBackgroundResource(R.drawable.gif_pressed);
                btnNaocan.setBackgroundResource(R.drawable.naocan);
                btnNencao.setBackgroundResource(R.drawable.nencao);
                btnQutu.setBackgroundResource(R.drawable.qutu);
                btnTucao.setBackgroundResource(R.drawable.tucao);


                //请求网络
                setActionBarTitle("GIF怪兽");
                kindId = 25;
                flag = true;
                kind = "recent_hot";
                url = String.format(URL1, String.valueOf(kindId), kind, "1", String.valueOf(size));
                executeHttp(url, URL2);
                slidingMenu.toggle();

                break;
            case R.id.sliding_naocan:
                btnBaozou.setBackgroundResource(R.drawable.ganhuo);
                btnGanhuo.setBackgroundResource(R.drawable.ganhuo);
                btnGif.setBackgroundResource(R.drawable.gif);
                btnNaocan.setBackgroundResource(R.drawable.naocan_pressed);
                btnNencao.setBackgroundResource(R.drawable.nencao);
                btnQutu.setBackgroundResource(R.drawable.qutu);
                btnTucao.setBackgroundResource(R.drawable.tucao);


                //请求网络
                setActionBarTitle("脑残对话");
                kindId = 295;
                flag = true;
                kind = "recent_hot";
                url = String.format(URL1, String.valueOf(kindId), kind, "1", String.valueOf(size));
                executeHttp(url, URL2);
                slidingMenu.toggle();
                break;
            case R.id.sliding_nencao:
                btnBaozou.setBackgroundResource(R.drawable.ganhuo);
                btnGanhuo.setBackgroundResource(R.drawable.ganhuo);
                btnGif.setBackgroundResource(R.drawable.gif);
                btnNaocan.setBackgroundResource(R.drawable.naocan);
                btnNencao.setBackgroundResource(R.drawable.nencao_pressed);
                btnQutu.setBackgroundResource(R.drawable.qutu);
                btnTucao.setBackgroundResource(R.drawable.tucao);

                //请求网络
                setActionBarTitle("最新更新");
                kindId = 1;
                kind = "latest";
                flag = true;
                url = String.format(URL1, String.valueOf(kindId), kind, "1", String.valueOf(size));
                executeHttp(url, URL2);
                slidingMenu.toggle();
                break;
            case R.id.sliding_qutu:
                btnBaozou.setBackgroundResource(R.drawable.ganhuo);
                btnGanhuo.setBackgroundResource(R.drawable.ganhuo);
                btnGif.setBackgroundResource(R.drawable.gif);
                btnNaocan.setBackgroundResource(R.drawable.naocan);
                btnNencao.setBackgroundResource(R.drawable.nencao);
                btnQutu.setBackgroundResource(R.drawable.qutu_pressed);
                btnTucao.setBackgroundResource(R.drawable.tucao);

                //请求网络
                setActionBarTitle("趣图百科");
                kindId = 24;
                flag = true;
                kind = "recent_hot";
                url = String.format(URL1, String.valueOf(kindId), kind, "1", String.valueOf(size));
                executeHttp(url, URL2);
                slidingMenu.toggle();
                break;
            case R.id.sliding_tucao:
                btnBaozou.setBackgroundResource(R.drawable.ganhuo);
                btnGanhuo.setBackgroundResource(R.drawable.ganhuo);
                btnGif.setBackgroundResource(R.drawable.gif);
                btnNaocan.setBackgroundResource(R.drawable.naocan);
                btnNencao.setBackgroundResource(R.drawable.nencao);
                btnQutu.setBackgroundResource(R.drawable.qutu_pressed);
                btnTucao.setBackgroundResource(R.drawable.tucao);
                //请求网络
                setActionBarTitle("神吐槽");
                kindId = 28;
                flag = true;
                kind = "recent_hot";
                url = String.format(URL1, String.valueOf(kindId), kind, "1", String.valueOf(size));
                executeHttp(url, URL2);
                slidingMenu.toggle();
                break;
        }
    }

    //////////////////////////联动效果设置/////////////////////////////////
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        int id = group.getId();

        if (id == R.id.topic_pager_switch) {
            int rbCount = group.getChildCount();

            // 处理步骤 2: 如果能够获取到RadioGroup中的每一个RadioButton
            //            我们判断以下RadioButton是否选中，
            //            我们采用循环来获取，如果选中，即可得到 索引位置
            //            容器提供 getChildAt(int index) 方法，来获取子控件

            int position = -1;

            for (int index = 0; index < rbCount; index++) {
                View v = group.getChildAt(index);
                if (v != null && v instanceof RadioButton) {
                    RadioButton rb = (RadioButton) v;
                    // 可以通过 RadioButton 的 isChecked() 判断是否选中了
                    if (rb.isChecked()) {
                        position = index;
                        break;
                    }
                }
            }

            Log.d("DetailActivity", "onCheckdChange " + position);

            if (position > -1) {
                pager.setCurrentItem(position, true);
            }
        } else {
            super.onCheckedChanged(group, checkedId);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
// 根据位置，找到RadioGroup中，所有的RadioButton
        // 设置指定索引位置的RadioButton选中。
        //

        View v = group.getChildAt(position);

        if (v != null) {
            if (v instanceof RadioButton) {
                RadioButton rb = (RadioButton) v;
                rb.setChecked(true);
                Log.d("DetailActivity", "onPageSelected setChecked");
            }
        }

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        int headerViewsCount = listView.getHeaderViewsCount();
        Article article = articles.get(position - headerViewsCount);
        Intent intent;

        if (!article.getPictures().equals("")) {
            String pictures = article.getPictures();
            intent = new Intent(this, TopicPicturesDetailActivity.class);
            intent.putExtra("pictures", pictures);
        } else {
            String mp4_file_link = article.getMp4_file_link();
            intent = new Intent(this, TopicPagerMovieActivity.class);
            intent.putExtra("mp4_file_link", mp4_file_link);
        }
        startActivity(intent);
    }
}

